package com.gjb6.master.common.web;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Keep;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.cncn.youmengsharelib.ui.SharePlatformsFragment;
import com.gjb6.master.account.AccountManager;
import com.gjb6.master.account.Login.ForgetActivity;
import com.gjb6.master.account.Login.LoginActivity;
import com.gjb6.master.account.ParamKey;
import com.gjb6.master.account.UrlCenter;
import com.gjb6.master.app.MyApplication;
import com.gjb6.master.app.home.MessageList;
import com.gjb6.master.app.storagemanager.GetUserInfo;
import com.gjb6.master.common.http.MyHttpRequest;
import com.gjb6.master.common.http.TokenInfo;
import com.gjb6.master.hxChat.ChatActivity;
import com.gjb6.master.messageDao.Info;
import com.gjb6.master.messageDao.InfoDao;
import com.gjb6.master.messageDao.Message;
import com.gjb6.master.messageDao.MessageDao;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.pachong.android.framework.citypicker.ChooseCityDialogFragment;
import com.pachong.android.framework.citypicker.Province;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.AppUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.NetUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/7/28
 * 移动端接口的实现类
 */
public class MobileFunImpl implements MobileImpable {
    private String locationProvider;
    private CommonWebviewFragment mFragment;
    private InfoDao infoDao;
    private String allMessage;
    String portrait1;
    String name1;
    String phone1;
    Info oldInfo1;
    private int chatType;
    private final static  String PORTRAIT ="http://osi16qzy2.bkt.clouddn.com/8ac9da68-ef50-4c5c-8662-83464a485768.png";
    public MobileFunImpl(CommonWebviewFragment fragment) {
        mFragment = fragment;
        getTokenInfo();
        getLocation();
    }

    @Keep
    @JavascriptInterface
    @Override
    public String getTokenInfo() {
        String token = null;
        if (AccountManager.isTokenValid()) {
            TokenInfo tokenInfo = AccountManager.getTokenInfo();
            token = tokenInfo.toString();
//            token = GsonUtils.toJson(tokenInfo);
        }
        return token;
    }

    /**
     * 获取本地极光推送消息
     */
    @Keep
    @JavascriptInterface
    @Override
    public String message(){
        MessageDao messageDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
        QueryBuilder<Message> messageQueryBuilder = messageDao.queryBuilder();
        List<Message> list = messageQueryBuilder.list();
        Collections.reverse(list);
        Log.e("list.toString()",list.toString());
        return list.toString();

    }

    /**
     * 删除系统消息 或者活动消息  0系统。1活动
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void cleanMessage(int type) {
        MessageDao messageDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
        QueryBuilder<Message> messageQueryBuilder = messageDao.queryBuilder();
        List<Message> list = messageQueryBuilder.list();
        Log.e("list.toString()",list.toString());
        for (int i=0;i<=list.size();i++){
            if(list.get(i).getType().equals(type+"")){
                messageDao.deleteByKey(list.get(i).getId());
            }
        }

        Collections.reverse(list);
    }


    /**
     * 发起聊天
     */
    @Keep
    @JavascriptInterface
    @Override
    public void EaseChat(String phone,String customerName,String customerPortrait,String masterName,String masterPortrait){
        if(phone.equals(AccountManager.getCurrentAccount().getPhone())){
            EasyToast.showToast(getContext(),"同一手机号不能聊天");
        }else{
        //点击后将对方名字头像保存下来
            if(phone.length()>11){
                String[] split = phone.split("_");
                phone1 = split[0];
                chatType=2;
            }else{
                phone1 = phone;
                chatType=1;
            }
        infoDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getInfoDao();
        Info oldInfo = infoDao.queryBuilder().where(InfoDao.Properties.Phone.eq(phone1)).unique();
            if(oldInfo!=null) {
                MyHttpRequest request = new MyHttpRequest(getContext());
                UrlParams urlParams = new UrlParams();
                urlParams.put("phone", phone1);
                urlParams.put("type", chatType + "");
                request.get(UrlCenter.GET_USER_INFO, urlParams, new DataRequestListener<GetUserInfo>(GetUserInfo.class) {
                            @Override
                            public void onStart(Context context, String url) {
                                super.onStart(context, url);
                            }
                            @Override
                            public void onSuccess(GetUserInfo o) {
                                super.onSuccess(o);
                                Log.e("onSuccess",o.toString());
                                Long id = oldInfo.getId();
                                infoDao.deleteByKey(id);
                                Info info = new Info(phone1, o.getNick_name(), o.getAvatar());
                                infoDao.insert(info);
                                List<Info> list = infoDao.queryBuilder().build().list();
                                Intent intent = new Intent(getContext(), ChatActivity.class);
                                intent.putExtra(ParamKey.CUSTOMERNAME,o.getNick_name());
                                intent.putExtra(ParamKey.CUSTOMERPORTRAIT,o.getAvatar());
                                intent.putExtra(ParamKey.MASTERNAME,masterName);
                                intent.putExtra(ParamKey.MASTERPORTRAIT,masterPortrait);
                                intent.putExtra(EaseConstant.EXTRA_USER_ID, phone);
                                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                                getContext().startActivity(intent);
                            }

                            @Override
                            public void onFailure(Throwable t, int errorNo, String strMsg) {
                                super.onFailure(t, errorNo, strMsg);
                            }
                        });
        }
        else {
                MyHttpRequest request = new MyHttpRequest(getContext());
                UrlParams urlParams = new UrlParams();
                urlParams.put("phone", phone1);
                urlParams.put("type", chatType + "");
                request.get(UrlCenter.GET_USER_INFO, urlParams, new DataRequestListener<GetUserInfo>(GetUserInfo.class){
                            @Override
                            public void onStart(Context context, String url) {
                                super.onStart(context, url);
                            }
                            @Override
                            public void onSuccess(GetUserInfo o) {
                                super.onSuccess(o);
                                Info info = new Info(phone1, o.getNick_name(), o.getAvatar());
                                Log.e("onSuccess1",phone1+o.getNick_name()+o.getAvatar());
                                infoDao.insert(info);
                                List<Info> list = infoDao.queryBuilder().build().list();
                                Intent intent = new Intent(getContext(), ChatActivity.class);
                                intent.putExtra(ParamKey.CUSTOMERNAME,customerName);
                                intent.putExtra(ParamKey.CUSTOMERPORTRAIT,customerPortrait);
                                intent.putExtra(ParamKey.MASTERNAME,masterName);
                                intent.putExtra(ParamKey.MASTERPORTRAIT,masterPortrait);
                                intent.putExtra(EaseConstant.EXTRA_USER_ID,phone);
                                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                                getContext().startActivity(intent);

                            }

                            @Override
                            public void onFailure(Throwable t, int errorNo, String strMsg) {
                                super.onFailure(t, errorNo, strMsg);
                            }
                        });
        }
        }
    }
        /**
          * 获取会话列表list
          *
        */
        @JavascriptInterface
        public String getEaseChatList(){
            Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
            List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
            /**
             * lastMsgTime will change if there is new message during sorting
             * so use synchronized to make sure timestamp of last message won't change.
             */
            synchronized (conversations) {
                for (EMConversation conversation : conversations.values()) {
                    if (conversation.getAllMessages().size() != 0) {
                        sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    }
                }
            }
            try {
                // Internal is TimSort algorithm, has bug
                sortConversationByLastChatTime(sortList);
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<EMConversation> list = new ArrayList<EMConversation>();
            for (Pair<Long, EMConversation> sortItem : sortList) {
                list.add(sortItem.second);
            }
            InfoDao lastInfoDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getInfoDao();
            ArrayList<MessageList> ml = new ArrayList<>();
            ArrayList<String> isMessage = new ArrayList<>();

            for (int i=0;i<list.size();i++){
                MessageList msg =new MessageList();
                String body = list.get(i).getLastMessage().getBody().toString();
                String s1 = list.get(i).getMessageAttachmentPath().toString();
                String[] sp = s1.split("/");
                String phone = sp[sp.length - 1];
                String myPhone = sp[sp.length - 2];
                List<EMMessage> allMessages = list.get(i).getAllMessages();
                for (int j = 0; j < allMessages.size(); j++) {
                    if (allMessages.get(j).getFrom().equals(myPhone) == true) {
                        Log.e("00000", "我发起过消息");
                        isMessage.add("1");
                    }
                }
//                if (isMessage.size() == 0){
                    Log.e("我从没发起过消息","我从没发起过消息");
                    InfoDao infoDao1 = MyApplication.getDaoSession(MyApplication.getAppContext()).getInfoDao();
                if(phone.length()>11){
                     String[] split = phone.split("_");
                     String s = split[0];
                    oldInfo1 = infoDao1.queryBuilder().where(InfoDao.Properties.Phone.eq(s)).unique();
                }else{
                    oldInfo1 = infoDao1.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique();
                   }
                    try {
                         oldInfo1.toString();
                        }catch(NullPointerException npe){
                        AccountManager.getCurrentAccount().setIs_null(true);
                        }
                        if(AccountManager.getCurrentAccount().getIs_null()==true){
                            portrait1 = PORTRAIT;
                            if(phone.length()>11){
                                String[] split = phone.split("_");
                                String s = split[0];
                                name1 = s;
                            }else{
                                name1 = phone;
                            }

                            AccountManager.getCurrentAccount().setIs_null(false);
                        }else{
                            portrait1 = oldInfo1.getPortrait();
                            name1 = oldInfo1.getName();
                        }

                    String name = name1;
                    String portrait = portrait1;
                    String[] split = body.split(":");
                    String lastBody = null;
                    Info info = new Info(myPhone, name, portrait);
                    lastInfoDao.insert(info);
                    for (int s = 0; s < split.length; s++) {
                        if (split.length == 2) {
                            lastBody = split[1];
                        } else {
                            for (int z = 0; z < split.length; z++) {
                                if (split[0].equals("image")) {
                                    lastBody = "\"" + "[图片]" + "\"";
                                } else if(split[0].equals("voice")){
                                    lastBody = "\""+"[语音]"+"\"";
                                } else {
                                    lastBody = "\"" + "[表情]" + "\"";
                                }
                            }
                        }
                    }
                    msg.setBody(lastBody);
                    msg.setPortrait(portrait);
                    msg.setName(name);
                    msg.setPhone(phone);
                    ml.add(msg);
                    allMessage = ml.toString();

                }
//                else{
//                    String name = lastInfoDao.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique().getName();
//                    String portrait = lastInfoDao.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique().getPortrait();
//                    String[] split = body.split(":");
//                    Log.e("split.length",split.length+"");
//                    String lastBody = null;
//                    for (int s =0; s<split.length;s++){
//                        if(split.length==2){
//                            lastBody = split[1];
//                        }else{
//                            for(int z =0;z<split.length;z++){
//                                if(split[0].equals("image")){
//                                    lastBody="\""+"[图片]"+"\"";
//                                }else if(split[0].equals("voice")){
//                                    lastBody = "\""+"[语音]"+"\"";
//                                }else{
//                                    lastBody = "\""+"[表情]"+"\"";
////                            lastBody = body.substring(4, body.length());
//                                }
//                            }
//                        }
//                    }
//                    msg.setBody(lastBody);
//                    Log.e("lastBody",lastBody);
//                     msg.setPortrait(portrait);
//                    msg.setName(name);
//                    msg.setPhone(phone);
//                    ml.add(msg);
//
//                }
//            }
//            Log.e("allMessageallMessage", "进来了");
//            if (allMessage == null) {
//                Log.e("allMessageallMessage1", ml.toString());
                return allMessage;
//            mFragment.getWebview().loadUrl("javascript:onMessage(ml.toString())");
//            } else {
//                Log.e("allMessageallMessage", allMessage);
////            mFragment.getWebview().loadUrl("javascript:onMessage(allMessage)");
//                return allMessage;
//            }
        }


    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    /**
     * 返回经纬度
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public String getLocation() {
        if(AccountManager.getCurrentAccount().getLongitude()!=null){
            return AccountManager.getCurrentAccount().getLongitude();
        }else{
            return "null";
        }
    }

    /**
     * 获取用户已读状态
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void getRead(String id, String type) {
        Long aLong = Long.valueOf(id);
        int integer = Integer.valueOf(id);
        MessageDao messageDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
        Message message = new Message((long) integer, type, messageDao.load(aLong).getData());
        messageDao.insertOrReplace(message);
        messageDao.insertInTx(message);
        QueryBuilder<Message> messageQueryBuilder = messageDao.queryBuilder();
        List<Message> list = messageQueryBuilder.list();
        Log.e("listto",list.toString());
    }

    @Keep
    @JavascriptInterface
    @Override
    public void login() {
        Log.d("kyluzoi", "web use login");
    }

    @Keep
    @JavascriptInterface
    @Override
    public void uploadImage(String tag) {
        Log.d("kyluzoi", "web use uploadimage");
        /*PhotoAlertFragment photoAlertFragment = new PhotoAlertFragment();
        photoAlertFragment.show(getActivity().getFragmentManager(), "tag");
        photoAlertFragment.setOnCitySelectedListener(this);
        mSynTag = tag;*/
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showToast(String url) {
//        return mConnectable.callback();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void share(String title, String content, String imgUrl, String targetUrl) {
        SharePlatformsFragment fragment = SharePlatformsFragment.newInstance(title, content, imgUrl, targetUrl);
        fragment.setShareListener(new ShareListener() {
            @Override
            public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "分享失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "取消分享", Toast.LENGTH_SHORT).show();
            }
        });
        fragment.show(mFragment.getFragmentManager(), "");
    }

    @Keep
    @JavascriptInterface
    @Override
    public void back() {
        mFragment.getActivity().finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public void hideTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public boolean netIsAvalible() {
        return NetUtil.isAvalible(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public int getVersionCode() {
        return AppUtil.getVersionCode(mFragment.getActivity());
    }

    //忘记密码
    @Keep
    @JavascriptInterface
    @Override
    public void forgetWord() {
        //弹出Dialog
        ForgetActivity.start(mFragment.getActivity(),2);
    }


    @JavascriptInterface
    @Override
    public void tocleanCache() {
        //清除缓存
        final File cacheDir =mFragment.getActivity().getCacheDir();
        final String cacheSize = FileUtils.size(cacheDir);
        //弹出Dialog
        showCacheDialog(cacheDir, cacheSize);
    }

    private void showCacheDialog(File cacheDir, String cacheSize) {
        if ("0B".equals(cacheSize)) {
            final AlertDialogFragment nullCacheDialogFrag = new AlertDialogFragment();
            nullCacheDialogFrag.setMessage("无缓存")
                    .setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            nullCacheDialogFrag.dismiss();
                        }
                    }).show(mFragment.getFragmentManager());
        }else{
            final AlertDialogFragment cleanDialogFrag = new AlertDialogFragment();
            cleanDialogFrag.setMessage("确认清除" + cacheSize + "缓存?")
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cleanDialogFrag.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            FileUtils.delFilesFromPath(cacheDir);
                            cleanDialogFrag.dismiss();
                            Toast.makeText(getContext(), "已清除" + cacheSize + "缓存!", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .show(mFragment.getFragmentManager());
        }
    }

    @Keep
    @JavascriptInterface
    @Override
    public void  showRegionActionssheet(String info){
        ChooseCityDialogFragment chooseCityDialog = new ChooseCityDialogFragment();
        chooseCityDialog.show(mFragment.getChildFragmentManager());
        chooseCityDialog.setOnCitySelectedListener(new ChooseCityDialogFragment.OnCitySelectedListener() {
            @Override
            public void onSelected(Province province, Province.City city, Province.Country country) {
                String s = "{"+ "\"province\":"+"{"+"\"code\":"+"\""+province.code+'\"'+","+"\"label\":"+"\""+province.label+'\"'+"}"+
                        ", \"city\":"+"{"+"\"code\":"+"\""+city.code+'\"'+","+"\"label\":"+"\""+city.label+'\"'+"}"+
                        ", \"district\":" +"{"+ "\"code\":"+"\""+country.code+'\"'+","+"\"label\":"+"\""+country.label+'\"'+"}"+
                        '}';
//                Log.e("sssssss", s);
//                EventBus.getDefault().post(s);
                mFragment.callLoadUrl(s);
//                mFragment.getWebview().callJsFunction("onUploadSuccess", s);

            }
        });
    }


    //退出登录
    @Keep
    @JavascriptInterface
    @Override
    public void logOut() {
        //弹出Dialog
        showCacheDialog();
//        getMessageDao().deleteAll();
    }

    private void showCacheDialog() {
        final AlertDialogFragment dialogOutFragment = new AlertDialogFragment();
        dialogOutFragment.setMessage("是否确定退出？").setNegativeButton("取消",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogOutFragment.dismiss();
                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AccountManager.getTokenInfo().clear();
                        dialogOutFragment.dismiss();
                        //避免返回到退出的界面
                        mFragment.getActivity().finish();
                        //环信退出登录
                        EMClient.getInstance().logout(true);
                        LoginActivity.start(mFragment.getContext());
                    }
                })
                .show(mFragment.getFragmentManager());
    }



    public static MessageDao getMessageDao() {
        return MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
    }
    //上下文
    private Context getContext() {
        return mFragment.getContext();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
}
